# -*- coding:utf-8 -*-
from fastapi import Request, HTTPException
from sqlalchemy.exc import OperationalError
from sqlalchemy import select, text
from app.entity.system import SysOrg, CreateSysOrg, UpdateSysOrg
from core.curd import IBaseDao, CRUDBase

BaseDao = CRUDBase(SysOrg)


class SysOrgDao(IBaseDao):
    """
    测试模块服务层
    """

    def __init__(self, req: Request):
        self.db_session = req.app.state.db_async_session
        self.base = CRUDBase(SysOrg)

    async def select_all(self):
        async with self.db_session() as db:
            try:
                ret = await self.query(
                    select(SysOrg.id, SysOrg.name, SysOrg.pid, SysOrg.status, SysOrg.code, SysOrg.sort).order_by(
                        SysOrg.sort))

                return list(
                    map(lambda x: {"id": x[0], "name": x[1], "pid": x[2], "status": x[3], "code": x[4], "sort": x[5],
                                   "children": []}, ret))

            except OperationalError as e:
                raise HTTPException(status_code=500, detail=str(e))
            except Exception as e:
                raise HTTPException(status_code=500, detail=str(e))
            finally:
                await db.close()

    @classmethod
    async def instance(cls, req: Request):
        return cls(req)
